package com.schoolgard.action.configuration;

import java.util.Date;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import net.sf.json.JSONObject;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;

import com.schoolegard.services.DeviceService;
import com.schoolegard.services.OrganizationService;
import com.schoolegard.services.ParamServerService;
import com.schoolegard.services.RegionsService;
import com.schoolegard.services.UpgradeToDeviceService;
import com.schoolgard.base.BaseAction;
import com.schoolgard.entitybean.Device;
import com.schoolgard.entitybean.Organization;
import com.schoolgard.entitybean.ParamServer;
import com.schoolgard.entitybean.ParamServerToDevice;
import com.schoolgard.entitybean.Regions;
import com.schoolgard.entitybean.Users;

public class ParamServerAction extends BaseAction{
    
	private static Logger logger = Logger.getLogger(ParamServerAction.class);
	private static final long serialVersionUID = 201112052117L;
	
	
	private ParamServerService paramServerService;
	private RegionsService regionsService;
	private OrganizationService organizationService;
	private DeviceService deviceService;
	private UpgradeToDeviceService upgradeToDeviceService;
	private ParamServer pars;
	
	public ParamServerToDevice serverToDevice;
	
	public void findByDeviceId()
	{
		String deviceId = request.getParameter("deviceId");
		if(StringUtils.isBlank(deviceId)) return;
		ParamServer paramServer = paramServerService.findByDeviceId(deviceId.replace("de_", ""));
		writeToResponse(JSONObject.fromObject(paramServer).toString());
	}
	
	public void saveParamserver(){
		//deviceIds可能包含区域的id，可能有组织的id，可能有设备的ID，终端的ID，所以要计算出来，最后只剩下设备的ID和终端的ID
		String deviceIds = request.getParameter("deviceIds");
		if(StringUtils.isBlank(deviceIds)){
			writeToResponse("0");
			return;
		}
		String[] deArray = deviceIds.split(","); //获得数组
		Set<String> ida = filterID(deArray); //获取所有设备和终端id
		Iterator<String> it = ida.iterator();
		ParamServer paremServer = null;
		while(it.hasNext()){
			String id = it.next();
			paremServer = paramServerService.findByDeviceId(id);
			Device device = deviceService.findById(id);
			if(paremServer == null){
				paremServer = new ParamServer();
				paremServer.setGuid(id);
			}
			paremServer.setBackupServerIp(pars.getBackupServerIp());
			paremServer.setComParam(pars.getComParam());
			paremServer.setDevice(deviceService.findById(id));
			paremServer.setHasAudio(pars.getHasAudio());
			paremServer.setIp(pars.getIp());
			paremServer.setManagerServerIp(pars.getManagerServerIp());
			paremServer.setManagerServerPwd(pars.getManagerServerPwd());
			paremServer.setManagerServerUser(pars.getManagerServerUser());
			paremServer.setName(device.getName());
			paremServer.setPortCtrl(pars.getPortCtrl());
			paremServer.setPortData(pars.getPortData());
			paremServer.setPortFtp(pars.getPortFtp());
			paremServer.setPortHttp(pars.getPortHttp());
			paremServer.setTerminalCount(pars.getTerminalCount());
			try{
				//生成任务
				ParamServerToDevice job = saveServerJob(paremServer,device);
				paramServerService.saveParamAndJob(paremServer,job);
			}catch (Exception e) {
				e.printStackTrace();
				writeToResponse("0");
				return;
			}
		}
		writeToResponse("1");		
	}
	
	private Set<String>  filterID(String[] fa)
	{
		Set<String> deteIds = new HashSet<String>(); //保证不会重复加入id
		for (String id : fa) {
			if(id.indexOf("de_")!=-1){ //设备id直接加进来
				deteIds.add(id.replace("de_", ""));
			}/*else if(id.indexOf("te_")!=-1){ //终端id直接加进来
				deteIds.add(id);
			}*/
			if(id.indexOf("re_")!=-1){ //区域
				deteIds.addAll(findByRegions(Long.valueOf(id.replace("re_", ""))));
			}else if(id.indexOf("or_")!=-1){ //组织
				deteIds.addAll(findByOrganization(Long.valueOf(id.replace("or_", ""))));
			}
		}
		return deteIds;
	}
	
	private Set<String> findByRegions(Long regionsId)
	{
		Set<String> deteIds = new HashSet<String>();
		List<Regions> children_regions = regionsService.findListByParentId(regionsId);
		List<Organization> organization = organizationService.findByRegions(regionsId);
		for(int i=0 ; i<organization.size() ; i++){
			deteIds.addAll(findByOrganization(organization.get(i).getId()));
		}
		if(children_regions != null && children_regions.size() > 0){
			for(int j=0 ; j<children_regions.size() ; j++){
				deteIds.addAll(findByRegions(children_regions.get(j).getId()));
			}
		}
		return deteIds;
	}
	
	private Set<String> findByOrganization(Long orgId)
	{
		Set<String> deteIds = new HashSet<String>();
		List<Device> devices = deviceService.findByOrganization(orgId);
		List<Organization> children_org = organizationService.findByParentId(orgId);
		for (Device device : devices) {
			deteIds.add(device.getGuid());
			//deteIds.addAll(findTerByDevice(device.getGuid())); //终端无需设置
		}
		for(int i= 0 ;i<children_org.size() ; i++){
			deteIds.addAll(findByOrganization(children_org.get(i).getId()));
		}
		return deteIds;
	}
	
	/*private Set<String> findTerByDevice(String devId)
	{
		Set<String> deteIds = new HashSet<String>();
		List<Terminal> terminals = terminalService.findByDevice(devId);
		for (Terminal terminal : terminals) {
			deteIds.add("te"+terminal.getGuid());
		}
		return deteIds;
	}*/
	
	private ParamServerToDevice saveServerJob(ParamServer paremServer,Device device){
		String jobModeId = request.getParameter("jobModeId");
		String guid = paremServer.getGuid();
		ParamServerToDevice job = new ParamServerToDevice();
		job.setCreateDatetime(new Date());
		job.setStartTime(serverToDevice.getStartTime());
		job.setRouter(deviceService.findRouter(device));
		job.setGuid(guid);
		job.setDeviceName(device.getName());
		job.setJobMode(upgradeToDeviceService.findJobModeById(StringUtils
				.isNotBlank(jobModeId) ? Long.valueOf(jobModeId) : 0));
		job.setJobStatus(upgradeToDeviceService.findjobStatusById(100L));
		Users user = (Users) session.get("user");
		if (user != null) {
			job.setUserId(user.getId());
			job.setUserName(user.getName());
		} 
		return job;
	}
	
	
	public void setParamServerService(ParamServerService paramServerService) {
		this.paramServerService = paramServerService;
	}
	public ParamServer getPars() {
		return pars;
	}
	public void setPars(ParamServer pars) {
		this.pars = pars;
	}
	public void setRegionsService(RegionsService regionsService) {
		this.regionsService = regionsService;
	}
	public void setOrganizationService(OrganizationService organizationService) {
		this.organizationService = organizationService;
	}
	public void setDeviceService(DeviceService deviceService) {
		this.deviceService = deviceService;
	}

	public ParamServerToDevice getServerToDevice() {
		return serverToDevice;
	}

	public void setServerToDevice(ParamServerToDevice serverToDevice) {
		this.serverToDevice = serverToDevice;
	}

	public void setUpgradeToDeviceService(
			UpgradeToDeviceService upgradeToDeviceService) {
		this.upgradeToDeviceService = upgradeToDeviceService;
	}
}
